import React, { useState, useEffect } from 'react'
import { Card, Form, Input, Button, Upload, message, Row, Col, Avatar, Tag, Divider, List } from 'antd'
import { useNavigate } from 'react-router-dom'
import { UserOutlined, CameraOutlined, EditOutlined, SaveOutlined, ArrowLeftOutlined, SafetyOutlined, BookOutlined, HeartOutlined } from '@ant-design/icons'

interface UserProfile {
  id: string
  username: string
  email: string
  phone: string
  village: string
  cropType: string
  joinDate: string
  avatar: string
  realName: string
  idCard: string
  address: string
  experience: number // 种植经验（年）
}

interface Activity {
  id: string
  title: string
  type: 'training' | 'event' | 'learning' | 'interaction'
  date: string
  status: 'completed' | 'ongoing' | 'registered'
}

const Profile: React.FC = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const [profile, setProfile] = useState<UserProfile | null>(null)
  const [loading, setLoading] = useState(true)
  const [editing, setEditing] = useState(false)
  const [activities, setActivities] = useState<Activity[]>([])

  // 模拟用户数据
  useEffect(() => {
    const mockProfile: UserProfile = {
      id: '1',
      username: '张大山',
      email: 'zhangdashan@example.com',
      phone: '13800138000',
      village: '幸福村',
      cropType: '水稻',
      joinDate: '2023-01-15',
      avatar: '',
      realName: '张大山',
      idCard: '110101199001011234',
      address: '幸福村三组28号',
      experience: 8
    }

    const mockActivities: Activity[] = [
      {
        id: '1',
        title: '现代农业技术培训',
        type: 'training',
        date: '2024-01-10',
        status: 'completed'
      },
      {
        id: '2',
        title: '春季种植交流会',
        type: 'event',
        date: '2024-01-15',
        status: 'registered'
      },
      {
        id: '3',
        title: '水稻病虫害防治课程',
        type: 'learning',
        date: '2024-01-08',
        status: 'completed'
      },
      {
        id: '4',
        title: '技术交流社区讨论',
        type: 'interaction',
        date: '2024-01-12',
        status: 'ongoing'
      }
    ]

    setTimeout(() => {
      setProfile(mockProfile)
      setActivities(mockActivities)
      setLoading(false)
      form.setFieldsValue(mockProfile)
    }, 1000)
  }, [form])

  // 保存个人信息
  const handleSave = async () => {
    try {
      const values = await form.validateFields()
      setProfile({ ...profile!, ...values })
      setEditing(false)
      message.success('个人信息更新成功')
    } catch (error) {
      message.error('请检查表单填写是否正确')
    }
  }

  // 取消编辑
  const handleCancel = () => {
    setEditing(false)
    form.setFieldsValue(profile)
  }

  // 头像上传
  const handleAvatarUpload = (info: any) => {
    if (info.file.status === 'done') {
      message.success('头像上传成功')
      // 实际应用中这里应该更新用户头像URL
    }
  }

  const getActivityIcon = (type: string) => {
    switch (type) {
      case 'training': return <BookOutlined style={{ color: '#1890ff' }} />
      case 'event': return <UserOutlined style={{ color: '#52c41a' }} />
      case 'learning': return <SafetyOutlined style={{ color: '#faad14' }} />
      case 'interaction': return <HeartOutlined style={{ color: '#eb2f96' }} />
      default: return <UserOutlined />
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'success'
      case 'ongoing': return 'processing'
      case 'registered': return 'warning'
      default: return 'default'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'completed': return '已完成'
      case 'ongoing': return '进行中'
      case 'registered': return '已报名'
      default: return status
    }
  }

  if (loading) {
    return <div style={{ padding: '24px', textAlign: 'center' }}>加载中...</div>
  }

  return (
    <div style={{ padding: '24px', background: '#f5f5f5', minHeight: '100vh' }}>
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <Button 
              type="text" 
              icon={<ArrowLeftOutlined />} 
              onClick={() => navigate('/user-dashboard')}
              style={{ padding: '4px 8px' }}
            >
              返回
            </Button>
            <span>个人中心</span>
          </div>
        }
        style={{ marginBottom: '24px' }}
        extra={
          !editing ? (
            <Button type="primary" icon={<EditOutlined />} onClick={() => setEditing(true)}>
              编辑信息
            </Button>
          ) : (
            <div style={{ display: 'flex', gap: '8px' }}>
              <Button onClick={handleCancel}>取消</Button>
              <Button type="primary" icon={<SaveOutlined />} onClick={handleSave}>
                保存
              </Button>
            </div>
          )
        }
      >
        <Row gutter={24}>
          {/* 左侧 - 个人信息 */}
          <Col span={16}>
            <Form
              form={form}
              layout="vertical"
              disabled={!editing}
            >
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label="用户名"
                    name="username"
                    rules={[{ required: true, message: '请输入用户名' }]}
                  >
                    <Input prefix={<UserOutlined />} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="真实姓名"
                    name="realName"
                    rules={[{ required: true, message: '请输入真实姓名' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label="电子邮箱"
                    name="email"
                    rules={[
                      { required: true, message: '请输入邮箱' },
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="联系电话"
                    name="phone"
                    rules={[{ required: true, message: '请输入联系电话' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label="所在村庄"
                    name="village"
                    rules={[{ required: true, message: '请选择所在村庄' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="主要种植类型"
                    name="cropType"
                    rules={[{ required: true, message: '请选择种植类型' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                label="详细地址"
                name="address"
                rules={[{ required: true, message: '请输入详细地址' }]}
              >
                <Input.TextArea rows={2} />
              </Form.Item>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label="身份证号"
                    name="idCard"
                    rules={[{ required: true, message: '请输入身份证号' }]}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item label="种植经验">
                    <Input value={`${profile?.experience} 年`} disabled />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Col>

          {/* 右侧 - 头像和统计信息 */}
          <Col span={8}>
            <div style={{ textAlign: 'center' }}>
              <Upload
                name="avatar"
                listType="picture-card"
                showUploadList={false}
                action="/api/upload"
                onChange={handleAvatarUpload}
                disabled={!editing}
              >
                <Avatar
                  size={100}
                  icon={<UserOutlined />}
                  src={profile?.avatar}
                  style={{ marginBottom: '16px' }}
                />
                {editing && (
                  <div style={{ marginTop: '8px' }}>
                    <CameraOutlined />
                    <div>更换头像</div>
                  </div>
                )}
              </Upload>
              
              <h3 style={{ marginTop: '16px' }}>{profile?.username}</h3>
              <Tag color="blue">{profile?.village}</Tag>
              <Tag color="green">{profile?.cropType}种植</Tag>
              
              <Divider />
              
              <div style={{ textAlign: 'left' }}>
                <h4>账户信息</h4>
                <p>注册时间: {profile?.joinDate}</p>
                <p>用户ID: {profile?.id}</p>
              </div>
            </div>
          </Col>
        </Row>

        <Divider />

        {/* 最近活动 */}
        <div>
          <h3>最近活动</h3>
          <List
            dataSource={activities}
            renderItem={activity => (
              <List.Item>
                <List.Item.Meta
                  avatar={getActivityIcon(activity.type)}
                  title={activity.title}
                  description={
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <span>{activity.date}</span>
                      <Tag color={getStatusColor(activity.status)}>
                        {getStatusText(activity.status)}
                      </Tag>
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        </div>
      </Card>
    </div>
  )
}

export default Profile